﻿/**
 
 @Name: layer拓展类，依赖于layer
 @Date: 2014.05.16
 @Author: 贤心
 @Versions：1.3
 @Api：http://www.sucaijiayuan.com
 @Desc: 本拓展会持续更新

 **/
layer.use('skin/layer.ext.css', function(){
    layer.ext && layer.ext();
});
layer.extv = '1.3';


/**

 系统prompt
 2014.5.11
 By 贤心
 
**/

layer.prompt = function(parme, yes, no){
    var log = {}, parme = parme || {}, conf = {
        area: ['auto', 'auto'],
        offset: [parme.top || '200px', ''],
        title: parme.title || '信息',
        dialog: {
            btns: 2,
            type: -1,
            msg: '<input type="'+ function(){
                if(parme.type === 1){ //密码
                    return 'password';
                } else if(parme.type === 2) {
                    return 'file';
                } else {
                    return 'text';
                }
            }() +'" class="xubox_prompt xubox_form" id="xubox_prompt" value="" />',
            yes: function(index){
                var val = log.prompt.val();
                if(val === ''){
                    log.prompt.focus();
                } else if(val.replace(/\s/g, '').length > (parme.length || 1000)) {
                    layer.tips('最多输入'+ (parme.length || 1000) +'个字数', '#xubox_prompt', 2);
                } else {
                    layer.close(index);
                    yes && yes(val);
                }
                
            }, no: no
        }, success: function(){
            log.prompt = $('#xubox_prompt');
        }
    };
    if(parme.type === 3){
        conf.dialog.msg = '<textarea class="xubox_prompt xubox_form xubox_formArea" id="xubox_prompt"></textarea>'
    }
    return $.layer(conf);
};


/**

 tab层 v1.0.0
 2014.5.11
 By 贤心
 
**/

layer.tab = function(parme){
    var log = {}, parme = parme || {}, data = parme.data || [], conf = {
        type: 1,
        border: [0],
        area: ['auto', 'auto'],
        title: false,
        shade : parme.shade,
        offset: parme.offset,
        move: '.xubox_tabmove',
        closeBtn: false,
        page: {html: '<div class="xubox_tab" style="'+ function(){
            parme.area = parme.area || [];
            return 'width:'+ (parme.area[0] || '500px') +'; height:'+ (parme.area[1] || '300px') +'">';
        }()
        +'<span class="xubox_tabmove"></span>'
        +'<div class="xubox_tabtit">'
        +function(){
            var len = data.length, ii = 1, str = '';
            if(len > 0){
                str = '<span class="xubox_tabnow">'+ data[0].title +'</span>';
                for(; ii < len; ii++){
                    str += '<span>'+ data[ii].title +'</span>';
                }
            }
            return str;
        }() +'</div>'
        +'<ul class="xubox_tab_main">'+ function(){
            var len = data.length, ii = 1, str = '';
            if(len > 0){
                str = '<li class="xubox_tabli xubox_tab_layer">'+ (data[0].content || 'content未传入') +'</li>';
                for(; ii < len; ii++){
                    str += '<li class="xubox_tabli">'+ (data[ii].content || 'content未传入') +'</li>';
                }
            }
            return str;
        }() +'</ul>'
        +'<span class="xubox_tabclose" title="关闭">X</span>'
        +'</div>'
        }, success: function(layerE){
            //切换事件
            var btn = $('.xubox_tabtit').children(), main = $('.xubox_tab_main').children(), close = $('.xubox_tabclose');
            btn.on('click', function(){
                var othis = $(this), index = othis.index();
                othis.addClass('xubox_tabnow').siblings().removeClass('xubox_tabnow');
                main.eq(index).show().siblings().hide();
            });
            //关闭层
            close.on('click', function(){
                layer.close(layerE.attr('times'));
            });
        }
    };
    return $.layer(conf);
};



/**

 相册层 v1.0.0
 2014.5.11
 By 贤心
 
**/


layer.photos = function(options){
    options = options || {};
    var log = {
        imgIndex: 1,
        end: null,
        html: $('html')
    }, win = $(window), json = options.json, page = options.page;
    //zh
    log.allImgs = $(page.parent).find('img');
    log.rotate = 0;
    if(json){
        var data = json.data;
        if(json.status === 1){
            log.imgLen = data.length;
            if(data.length > 0){
                log.thissrc = data[json.start].src;
                log.pid = data[json.start].pid;
                log.imgsname = (json.title || '');
                log.name = data[json.start].name;
                log.imgIndex = json.start + 1;
            } else {
                layer.msg('没有任何图片', 2, 8);
                return;
            }
            
        } else {
            layer.msg('未请求到数据', 2, 8);
            return;
        }
    } else {
        var imgs = $(page.parent).find('img'), nowimg = imgs.eq(page.start);
        log.thissrc = (nowimg.attr('layer-img') || nowimg.attr('src'));
        log.pid = nowimg.attr('pid');
        log.imgLen = imgs.length;
        log.imgsname = (page.title || '');
        log.name = nowimg.attr('layer-pname');
        log.imgIndex = page.start + 1;
        log.nowImgName = nowimg.attr('data-name');
    }
    
    var conf = {
        type: 1,
        border: [0],
        area: [(options.html ? 915 : 600) + 'px', 'auto'],
        title: false,
        shade: [.9, '#000', true],
        shadeClose: true,
        offset: ['25px', ''],
        bgcolor: '',
        page: {
            html: '<div class="zh_c"><div class="xubox_bigimg"><div class="zh_imghover">'+
            	'<div class="zh_imgcenter">'+
            	'<div id="zh_enlargediv" class="zh_imgcenter">'+
            	'<img class="zh_bigImg" style="width: 100%;top:0; height: 100%;" src="'+ log.thissrc +'" alt="'+ (log.name || '') +'" layer-pid="'+ (log.pid || '') +'" onclick="zh_extent.imgClick()">'
            	+'<div class="zh_enlarge4276">'+function(){//放大板块
            	
            }()+'</div>'+
            	'</div></div><div class="xubox_imgsee">'+ function(){
                if(log.imgLen > 1){
                    return '<a id="zhImgPrev" href="" class="xubox_iconext xubox_prev"></a><a id="zhImgNext" href="" class="xubox_iconext xubox_next"></a>'
                } else {
                    return '';
                }   
            }() +'<div class="xubox_imgbar"><div class="xubox_imgtit">'+
            		'<span><a href="javascript:void(0);">'+ log.imgsname +' </a><em>'+ log.imgIndex +'/'+ log.imgLen +'</em></span>'+
            		'<span id="imgNamezh"><a href="javascript:void(0);" title="'+ log.nowImgName +'">'+ log.nowImgName +' </a></span>'+
            		'<span class="zh_bottomright"><a href="javascript:void(0);" style="display:none" id="rotateImg">旋转</a><a href="javascript:void(0);" id="imgEnlarge" onclick="zh_extent.enlarge()">放大</a></span>'+
            		'</div></div></div>'+
            	'</div><div class="zh_imglist">'+function(){
            	//加载图片缩略图列表
            	var imgLst = log.allImgs;
            	var len = imgLst.length;
            	/*
            	var prev = '<div class="zh_list_prev"><a href="javascript:void(0);"><img class="zh_specialImg" src="system/layer/skin/default/left.png" onclick="zh_extent.imgLstPrev()"></a></div>';
            	var next = '<div class="zh_list_next"><a href="javascript:void(0);"><img class="zh_specialImg" src="system/layer/skin/default/right.png" onclick="zh_extent.imgLstNext()"></a></div>'
            	*/	
            	var prev = '<div class="zh_list_prev"><a href="javascript:void(0);" class="zh_specialImg_font zh_specialImg glyphicon glyphicon-chevron-left" onclick="zh_extent.imgLstPrev()"></a></div>';
            	var next = '<div class="zh_list_next"><a href="javascript:void(0);" class="zh_specialImg_font zh_specialImg glyphicon glyphicon-chevron-right" onclick="zh_extent.imgLstNext()"></a></div>';
            	
            	var imgsUL = '';
            	var current = '';
            	for(var i=0;i < len;i++){
            		if(imgLst[i].src.endsWith(log.thissrc)){
            			current = 'zh_current';
            		}else{ 
            			current = '';
            		}
            		imgsUL += '<li class="zh_imgsUL_li '+current+'"><a href="javascript:;"><img src="'+imgLst[i].src+'" class="zh_li_img"></a></li>';
            	}
            	return prev+'<div class="zh_samllArea"><ul class="zh_img_ul">'+imgsUL+'</ul></div>'+next;
            }()+'</div></div></div>'+ function(){
                if(options.html){
                    return '<div class="xubox_intro">'+ options.html +'</div>';
                } else {
                    return '';
                }
            }()
        }, success: function(layero){
            log.bigimg = layero.find('.xubox_bigimg');
            log.imgsee = log.bigimg.find('.xubox_imgsee');
            log.imgbar = log.imgsee.find('.xubox_imgbar');
            log.imgtit = log.imgbar.find('.xubox_imgtit');
            log.layero = layero;
            
            /*var img = log.imgs = log.bigimg.find('img');*/
            var img = log.imgs = log.bigimg.find('.zh_imghover').find('img');
            
            clearTimeout(log.timerr);
            log.timerr = setTimeout(function(){
                $('html').css('overflow', 'hidden').attr('layer-full', log.index);
            }, 10);
            
            img.load(function(){
                log.imgarea = [img.outerWidth(), img.outerHeight()];
                log.resize(layero);
                options.success && options.success(json || page);
            });
            
            log.event();
            
        }, end: function(){
            layer.closeAll();
            log.end = true;
        }
    };
    
    //一些动作
    log.event = function(){
    	//设置ul宽度
    	log.bigimg.find('.zh_img_ul').width(log.imgLen*(90+12)+log.bigimg.find('.zh_samllArea').width());
    	 log.bigimg.find('.zh_imghover').hover(function(){
    		 log.imgsee.show();
         }, function(){
             log.imgsee.hide();
    	 });
    	 //旋转图片
    	 $(".xubox_imgtit #rotateImg").rotate({ 
			   bind: 
			     { 
			        click: function(){
			        	/*log.rotate = (log.rotate==360)?0:log.rotate;*/
			        	log.rotate += 90;
			            $('.zh_bigImg').rotate({animateTo:log.rotate })
			        }
			     } 
			   
		});
    	 
    	 $('.zh_imgcenter .zh_enlarge4276').hide();
    	 
    	 zh_extent.scrollNow();//滚动到当前
    	 
    	 log.bigimg.find('li').click(function(){//点击图片切换
    		 var currIndex = $(".zh_samllArea .zh_current").index();
    		 var num = $(this).index();
    		 zh_extent.imgLstClick(num);
    		 log.imgIndex = num+1;
    		 log.tabimg();
    		 $(".xubox_prev").show();
         	 $(".xubox_next").show();
         	//是否滚动
            zh_extent.scroll(log.imgIndex,log.imgLen,2,currIndex);
    	 });
        //上一张
        conf.imgprev = function(){
        	$(".xubox_next").show();
        	
            if(log.imgIndex == 1){
                /*log.imgIndex = log.imgLen;*/
            	layer.msg('已经是第一张');
            	$(".xubox_prev").hide();
            }else{
            	//图片列表是否需要滚动
            	zh_extent.scroll(log.imgIndex,log.imgLen,0);
            	log.imgIndex--;
            	log.tabimg();
            }
        };
        log.bigimg.find('.xubox_prev').on('click', function(event){
            event.preventDefault();
            conf.imgprev();
        });
        
        //下一张
        conf.imgnext = function(){
        	$(".xubox_prev").show();
        	
            if(log.imgIndex == log.imgLen){
                /*log.imgIndex = 1;*/
            	layer.msg('已经是最后一张');
            	$(".xubox_next").hide();
            }else{
            	//图片列表是否需要滚动
            	zh_extent.scroll(log.imgIndex,log.imgLen,1);
            	log.imgIndex++;
            	log.tabimg();
            }
        };
        log.bigimg.find('.xubox_next').on('click', function(event){         
            event.preventDefault();
            conf.imgnext();
        });
        
        //方向键
        $(document).keyup(function(event){
            if(!log.end){
                var code = event.keyCode;
                event.preventDefault();
                if(code === 37){
                    conf.imgprev();
                } else if(code === 39) {
                    conf.imgnext();
                } else if(code === 27) {
                    layer.close(log.index);
                }
            }
        });
        
        
        log.tabimg = function(){
            var timer, src, pid, name;
            log.imgs.removeAttr('style');
            if(json){
                var nowdata = data[log.imgIndex - 1];
                src = nowdata.src;
                pid = nowdata.pid;
                name = nowdata.name;
            } else {
                var thisimg = imgs.eq(log.imgIndex - 1);
                src = thisimg.attr('layer-img') || thisimg.attr('src');
                pid = thisimg.attr('layer-pid') || '';
                name = thisimg.attr('layer-pname') || '';
                log.nowImgName = thisimg.attr('data-name');
            }
            log.imgs.attr({
                src: src,
                'layer-pid': pid,
                alt: name
            });
            log.imgtit.find('em').text(log.imgIndex + '/' + log.imgLen);
            log.imgtit.find('#imgNamezh').find('a').text(log.nowImgName).attr('title',log.nowImgName);
            log.imgsee.show();
            log.imgs.css('transform','');
            $('.zh_imgcenter .zh_bigImg').removeClass('zh_enlarge');
            $(".xubox_imgtit #imgEnlarge").text("放大");
            /*log.rotate = 0;*/
            //改变当前选中
            zh_extent.changeCurrentImg();
            
            $('.zh_imgcenter .zh_bigImg').show();
			$('.zh_imgcenter .zh_enlarge4276').hide();
        }
    };
    
    //相册响应式
    log.resize = function(layero){
        var relog = {}, wa = [win.width(), win.height()];
        relog.limit = wa[0] - wa[0]/wa[1]*(60*wa[0]/wa[1]);
        if(relog.limit < 600){
            relog.limit = 600;
        }
        var area = [relog.limit,  wa[1] > 400 ? wa[1] - 50 : 400];
        area[0] = options.html ? area[0] : (area[0] - 300);
        layer.area(log.index, {
            width: area[0] + (options.html ? 15 : 0),
            height: area[1]
        });
        relog.flwidth = area[0] - (options.html ? 300 : 0);
        if(log.imgarea[0] > relog.flwidth){
            log.imgs.css({width: relog.flwidth});
        } else {
            log.imgs.css({width: log.imgarea[0]});
        }
        if(log.imgs.outerHeight() < area[1]){
            log.imgs.css({top: (area[1] - log.imgs.outerHeight())/2});
        }
        log.imgs.css({visibility: 'visible'});
        log.bigimg.css({width: relog.flwidth, height: area[1], 'background-color': options.bgcolor});
        if(options.html){
            layero.find('.xubox_intro').css({height: area[1]});
        }
        //zh 全图显示
        log.imgs.css({
        	height:'100%',
        	width:'100%',
        	top:'0'
        });
        relog = null;
        wa = null;
        area = null;
    };
    
    win.on('resize', function(){
        if(log.end){
            return;
        }
        if(log.timer){
            clearTimeout(log.timer); 
        }
        log.timer = setTimeout(function(){
            log.resize(log.layero);
        }, 200); 
    });
    
    log.index = $.layer(conf);
    return log.index;
};

//获取页面元素包含的所有图片，快捷调用
layer.photosPage = function(options){
    var log = {};
    log.run = function(index){
        layer.photos({
            html: options.html,
            success: options.success,
            page: {
                title: options.title,
                id: options.id,
                start: index,
                parent: options.parent
            }
        });
    };
    options = options || {};
    $(options.parent).find('img').each(function(index){
        $(this).on('click', function(){
            log.run(index);
        });
    });
};

var zh_extent = {
		imgClick:function(){
			$("#zhImgNext").click();
		},
		imgLstPrev:function(){
			$("#zhImgPrev").click();
		},
		imgLstNext:function(){
			$("#zhImgNext").click();
		},
		changeCurrentImg:function(){
			$(".zh_samllArea li").removeClass("zh_current");
			var lstImgs = $(".zh_samllArea img");
			var currImg = $(".zh_imgcenter img");
			for(var i=0;i<lstImgs.length;i++){
				if(lstImgs[i].src.endsWith(currImg[0].src)){
					$(".zh_samllArea li:eq("+i+")").addClass("zh_current");
				}
			}
		},
		imgLstClick:function(num){//点击缩略图列表图片
			$(".zh_samllArea li").removeClass("zh_current");
			$(".zh_imgcenter img")[0].src =$(".zh_samllArea li img")[num].src;
			$(".zh_samllArea li:eq("+num+")").addClass("zh_current");
		},
		scroll:function(nowIndex,allNum,oper,prevIndex){//判定缩略图列表是否需要滚动
			var divWidth = $(".zh_samllArea").width();
			var ulWidth = $(".zh_img_ul").width();
			if(divWidth > ulWidth || ((nowIndex==allNum)&&((nowIndex*102)%divWidth <102))){ 
				return;
			}
			var liNum = $('.zh_samllArea .zh_current').index()+1;
			/*var maxShow = Math.ceil(divWidth/(90+12));*///同时最多显示数量
			var scrollWidth = ulWidth - divWidth;//li总宽度减去外层div的宽度。即得到滚动条需要滚动的长度 
			var scrleft = $(".zh_samllArea").scrollLeft();//目前滚动条的滚动长度
			if(oper == 1 ){
				//向右滚动
				if(!isNaN(scrollWidth) && (scrleft < scrollWidth)){  
		            $(".zh_samllArea").animate({"scrollLeft":scrleft+(90+12)},100); 
		        }  
			}else if(oper == 0 ){//向左滚动
				$(".zh_samllArea").animate({scrollLeft:(scrleft-(90+12))},100);
			}else if(oper == 2){//点击图片时
				var nowWidth = liNum*(90+12);
				var currIndex = $(".zh_samllArea .zh_current").index();
				if(prevIndex<=currIndex){
					if(!isNaN(scrollWidth) && (scrleft < scrollWidth)){
						$(".zh_samllArea").animate({"scrollLeft":scrleft+(90+12)*1},100); 
					}
				}else if(prevIndex>currIndex){//当前第一张
					if(scrleft>0) {//向左滚动
						$(".zh_samllArea").animate({scrollLeft:(scrleft-(90+12)*1)},100);
					}
				}
			}
		},
		scrollNow:function(){  //点击图片进入预览是滚动到当前图片
			var nowNum = $('.zh_samllArea .zh_current').index()+1;
			var divWidth = $(".zh_samllArea").width();
			if(nowNum*(90+12) > divWidth){
				$(".zh_samllArea").animate({"scrollLeft":(90+12)*(nowNum-1)},100); 
			}
		},
		rotate:function(value){//旋转
		},
		enlarge:function(){//放大
			var text = $(".xubox_imgtit #imgEnlarge").text();
			if(text == '放大'){
				/*$('.zh_imgcenter .zh_bigImg').addClass('zh_enlarge');*/
				$('.zh_imgcenter .zh_enlarge4276').empty();
				$(".xubox_imgtit #imgEnlarge").text("还原");
				$('.zh_imgcenter .zh_bigImg').hide();
				$('.zh_imgcenter .zh_enlarge4276').append(zh_extent.zh_enlargeHtml());
				$('.zh_imgcenter .zh_enlarge4276').show();
				$('[mag-thumb="outer-drag"]').mag({
				  mode: 'outer',
				  position: 'drag',
				  toggle: false
				});
			}else{
				/*$('.zh_imgcenter .zh_bigImg').removeClass('zh_enlarge');*/
				$(".xubox_imgtit #imgEnlarge").text("放大");
				$('.zh_imgcenter .zh_bigImg').show();
				$('.zh_imgcenter .zh_enlarge4276').hide();
				$('.zh_imgcenter .zh_enlarge4276').empty();
			}
			
		},
		zh_enlargeHtml:function(){  //放大图片
			var src = $('.zh_imgcenter .zh_bigImg')[0].src;
			var html = '<div class="zzsc-container">'+
        	'<div class="container mt50">'+
        	'<main>'+
			'<div class="row mag-eg-row">'+
				'<div class="mag-eg-el-wrap img-thumbnail">'+
					'<div class="proportion">'+
						'<div mag-thumb="outer-drag" class="mag-eg-el">'+
						  '<img style="width:100%" src="'+ src +'" />'+
						'</div>'+
						'<div class="filler"></div>'+
					  '</div>'+
				'</div>'+
				'<div class="mag-eg-el-wrap-large img-thumbnail">'+
				  '<div class="proportion">'+
					'<div mag-zoom="outer-drag" class="mag-eg-el" style="float: right;">'+
					  '<img src="'+ src +'" />'+
					'</div>'+
					'<div class="filler"></div>'+
				  '</div>'+
				'</div>'+
			'</div>'+
			'</main></div></div>';
			return html;
		}
}
